﻿using System;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using System.Timers;
using Avalonia.Controls.Notifications;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using SukiUI.Theme;

namespace Launcher;

public partial class MainModel : ObservableObject
{
    [ObservableProperty] private ChannelInfo _channelInfo = new();
    [ObservableProperty] private Channel? _activeChannel;
    [ObservableProperty] private string _availableFreeSpace = "--";
    [ObservableProperty] private bool _menuExpanded = true;

    private readonly MainWindow _mainWindow;

    public MainModel(MainWindow mainWindow)
    {
        _mainWindow = mainWindow;
        AppConfig.Load();
        Setting.Load();
        RequestChannelInfo(false);
        RefreshAvailableFreeSpace();
    }

    private async void RequestChannelInfo(bool showSuccessfully)
    {
        try
        {
            _mainWindow.RefreshButton.ShowProgress();
            _mainWindow.RefreshButton.IsEnabled = false;
            using (var response = await Utils.HttpClient.GetAsync(
                       $"{AppConfig.Instance.RequestInfoUrl}?platform={Utils.GetCurrentPlatform().ToString()}"))
            {
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                ChannelInfo = JsonSerializer.Deserialize<ChannelInfo>(json) ?? new();
            }

            if (ChannelInfo.Channels.Count == 0)
            {
                MainWindow.ShowToast(NotificationType.Warning, "警告", "没有可用渠道");
            }
            else if (showSuccessfully)
            {
                MainWindow.ShowToast(NotificationType.Information, "成功", "渠道信息已更新");
            }
        }
        catch (Exception e)
        {
            MainWindow.ShowToast(NotificationType.Error, "失败", "获取渠道信息失败");
            Console.Error.WriteLine(e);
        }
        finally
        {
            _mainWindow.RefreshButton.HideProgress();
            _mainWindow.RefreshButton.IsEnabled = true;
        }
    }

    [RelayCommand]
    private void OpenSettingWindow()
    {
        new SettingWindow(_mainWindow).ShowDialog(_mainWindow);
    }

    [RelayCommand]
    private void RefreshChannelInfo()
    {
        RequestChannelInfo(true);
    }

    private async void RefreshAvailableFreeSpace()
    {
        try
        {
            do
            {
                try
                {
                    var driverPath = Path.GetPathRoot(Path.GetFullPath(Setting.Instance.CachePath));
                    AvailableFreeSpace = "可用空间："+Utils.ByteSizeFormat(new DriveInfo(driverPath).AvailableFreeSpace);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e);
                }
                await Task.Delay(TimeSpan.FromSeconds(1));
            } while (true);
        }
        catch (Exception e)
        {
            Console.Error.WriteLine(e);
        }
    }
}